var createError = require('http-errors')
var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')
var cors = require('cors')

// 导入数据库模型
const db = require('./models')

// 导入路由
var indexRouter = require('./routes/index')
var usersRouter = require('./routes/users')
var apiRouter = require('./apis') // 导入API路由

var app = express()

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'hbs')

// 允许跨域请求
app.use(cors())

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

// 将io对象添加到请求中
app.use((req, res, next) => {
  req.io = app.get('io')
  next()
})

// 挂载路由
app.use('/', indexRouter)
app.use('/users', usersRouter)
app.use('/api', apiRouter) // 将API路由挂载到 /api 路径下

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404))
})

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}

  // 如果是API路由，返回JSON格式的错误
  if (req.path.startsWith('/api')) {
    return res.status(err.status || 500).json({
      success: false,
      message: err.message || '服务器内部错误',
      error: req.app.get('env') === 'development' ? err.stack : undefined,
    })
  }

  // 否则渲染错误页面
  res.status(err.status || 500)
  res.render('error')
})

module.exports = app
